package karileet.meeting.profile;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.Log;

/**
 * Class handles notification sound playing. Since audio is dependent on media
 * volume, this class escalates notification volume to 100 while playing beep.
 * When audio is done playing, sound settings are restored
 *
 * @author markus karileet
 */
public class SoundManager {
    MediaPlayer mPlayer;
    Context ctx;

    public SoundManager(Context ctx) {
        this.ctx = ctx;
    }

    public void play(final int beepVolume) {
//		MediaPlayer mp = new MediaPlayer();

        mPlayer = MediaPlayer.create(ctx, R.raw.beep_extended);

        if (mPlayer != null) {
            final AudioManager audioManager = (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE);
            final int old = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            Log.d(ProfileConf.APP, "Storing old media volume: " + old);
            Log.d(ProfileConf.APP, "Playing beep with volume: " + beepVolume);
            mPlayer.setOnPreparedListener(new OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                            beepVolume,
                            0);
                    Log.d(ProfileConf.APP, "Playing beep! " + audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
                    mp.setVolume(100, 100);
                }
            });
            mPlayer.setOnCompletionListener(new OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    Log.d(ProfileConf.APP, "Stopping audio and restoring values!");
                    mp.reset();
                    mp.release();
                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                            old,
                            0);
                }
            });

            mPlayer.start();
        }
    }
}